import { makeObservable,observable,action } from "mobx";
import { getCart,GetCartAns,addGood,AddGoodAns,updateCount } from "../../api/cart";
import Message from '../../components/Message/Message'

export interface ICartList {
    cid: string;
    idu: string;
    goodName: string;
    goodCount: number;
    goodId: number;
    goodcover: string;
    goodMethod: string;
    goodColor: string;
    goodSize: string;
    goodPrice: number;
}

class CartStore {
    constructor(){
        makeObservable(this)
    }
    @observable cartList: Array<ICartList | any>= [ ]

    //设置购物车数据
    @action.bound setCartList(list: Array<ICartList | any>){
        this.cartList = list
    }

    //async 异步action，请求用户购物车数据
    @action.bound getUserCart(){
        getCart()
           .then(res => {
               const {code,data} = res as unknown as GetCartAns
               if(code === 200 || code === 201){
                   this.setCartList(data)
               }
           })
           .catch(err => {
               console.log(err);
           })
    }

    //async 异步action，用户添加商品到购物车
    @action.bound userAddCart(goodId: number,goodName: string,goodCount: number,goodcover: string,goodMethod: string,goodColor: string,goodSize: string,goodPrice: number){
        addGood(goodId, goodName, goodCount, goodcover, goodMethod, goodColor, goodSize, goodPrice)
            .then(res => {
                const {code,msg} = res as unknown as AddGoodAns
                if(code === 200){
                    Message('success',msg)
                    this.getUserCart()
                }else{
                    Message('error',msg)
                }
            })
            .catch(err => {
                console.log(err)
            })
    }

    //改变购物车商品数量的同步action方法
    @action.bound userChangeCount(cId: string,num: number){
        for(let item of this.cartList){
            if(item.cid === cId){
                if(item.goodCount + num !== 0){
                    item.goodCount += num
                }
            }
        }
    }
    //async 异步action，用户更改购物车商品数量
    @action.bound userUpdateCount(cId: string,num: number){
        updateCount(cId,num)
            .then(res => {
                const {code,msg} = res as unknown as AddGoodAns
                if(code === 200){
                    //成功后更新购物车数据
                    this.userChangeCount(cId,num)
                }else{
                    Message('error',msg)
                }
            })
            .catch(err => {
                console.log(err)
            })
    }
}

export default CartStore